//
//  OAuthViewController.swift
//  weibo92
//
//  Created by Apple on 15/10/22.
//  Copyright © 2015年 miao. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {

    //MARK: -网页视图
    private lazy var webView = UIWebView()
    
    //关闭控制器
    @objc func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc func autofill(){
    
        let js = "document.getElementById('userId').value='miaopf123@sina.cn';"  + "document.getElementById('passwd').value='mimazhennanji92';"
      
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //MARK: -设置界面
    override func loadView() {
        ///设置OAuth 的视图
        view = webView
        //设置代理
        webView.delegate = self
   
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autofill")
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载页面
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.shareTools.oauthURL))
    }

}
//MARK:  -UIWebViewDelegate
extension OAuthViewController:UIWebViewDelegate{
    
    ///h
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //看看是否是百度
        guard let url = request.URL where url.host == "www.baidu.com" else{
            
            return true
        }

        //看看code ＝ 是否存在
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            return false
        }
        
        //获取授权码
      let code = query.substringFromIndex("code=".endIndex)
       
      /// 加载token
      AccountViewModel.shareAccountViewModel.loadAccessToken(code) { (isSuccess) -> () in
        if isSuccess{
            print("成功了")
        }else{
            print("失败了")
        }
    }

        return false
    }
}


